import BaseResponse from './BaseResponse';
import Constants from '../../common/Constants'
import { RequestOptions } from './HttpConfig';
import http from '@ohos.net.http';
import { Logger } from '../../common/Logger';

export default class Request {

  /**
   * 创建一个HttpRequest并发起请求
   * */
  createHttpRequest<T>(options: RequestOptions): Promise<BaseResponse<T>> {
    options.url = Constants.BaseUrl + options.url;

    let promise = new Promise<BaseResponse<T>>(async (resolve, reject) => {

      const pushOptions: http.HttpRequestOptions = {
        method: options.method,
        connectTimeout: Constants.CONNECT_TIMEOUT,
        readTimeout: Constants.READ_TIMEOUT,
        header: {
          'client_type': 'HarmonyOS',
          'Authorization': '',
          ...options.header,
        },
        extraData: options.extraData
      }

      Logger.debug(`Start ${options.method}`, options.url)
      Logger.debug('requestOptions', JSON.stringify(pushOptions))

      const httpRequest = http.createHttp();
      httpRequest.request(options.url, pushOptions).then((res) => {
        const result = JSON.parse(res.result.toString());
        Logger.debug(`responseCode=${res.responseCode}`)
        Logger.debug('header', JSON.stringify(res.header))
        if (result.code == Constants.SUCCESS_CODE) {
          Logger.debug('success', JSON.stringify(result))
          Logger.debug(`End ${options.method}`, options.url)
          resolve(result);
        } else {
          Logger.debug('error ', result)
          Logger.debug(`End ${options.method}`, options.url)
          reject(result);
        }
        httpRequest.destroy();
      }).catch((error) => {
        Logger.debug('error ', error)
        Logger.debug(`End ${options.method}`, options.url)
        reject(error);
      });
    })

    return promise;
  }
}